﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CTEM.Controllers.BUS;
using CTEM.Controllers.Global;
using CTEM.Models;
using CTEM.ModuleForms.EmployeeManagement;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using CTEM.ModuleForms.ManageEmployee;
using DevExpress.Data.Filtering;



namespace CTEM.ModuleForms.EmployeeManagement
{
    public partial class AdvanceManagement : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private List<EmployeeAdvanceDTO> _listAdvance;
        private readonly EmployeeBUS _empBus = new EmployeeBUS();
        private readonly string _advanceType;
        private readonly DateTime _fromDate;
        private readonly DateTime _toDate;
        private readonly EmployeeSalaryDTO _employeeSalary;
        private bool _isNew;
        private bool _isEdit;
        private bool _isUpdate;

        public AdvanceManagement(string advanceType, EmployeeSalaryDTO employeeSalary)
        {
            InitializeComponent();
            _isNew = false;
            _isUpdate = false;

            _advanceType = advanceType;
            _employeeSalary = employeeSalary;
            _employeeSalary.MonthFormat = DateTime.ParseExact(employeeSalary.Month + "01 00:00:00", "yyyyMMdd hh:mm:ss", null);
            var year = _employeeSalary.MonthFormat.Year;
            var month = _employeeSalary.MonthFormat.Month;

            _toDate = new DateTime(year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
            _fromDate = new DateTime(year, month, 1);

            gridView1.ActiveFilterCriteria = (new BinaryOperator("EmployeeID", employeeSalary.EmployeeID, BinaryOperatorType.Equal) &
            new BinaryOperator("DateAdvance", _fromDate, BinaryOperatorType.GreaterOrEqual) &
            (new BinaryOperator("DateAdvance", _toDate, BinaryOperatorType.LessOrEqual)));

            LoadData();
        }

        public long TotalAdvance (List<EmployeeAdvanceDTO> listAdvance)
        {
            long totalAdvance = 0;
            foreach (var employeeAdvanceDto in listAdvance)
            {
                if (employeeAdvanceDto.EmployeeID == _employeeSalary.EmployeeID && 
                    employeeAdvanceDto.DateAdvance >= _fromDate && 
                    employeeAdvanceDto.DateAdvance <= _toDate)
                totalAdvance += employeeAdvanceDto.TotalAdvance;
            }
            return totalAdvance;
        }

        private void LoadData()
        {
            _listAdvance = _empBus.LoadAdvanceByEmployeeID(_employeeSalary.EmployeeID, _fromDate, _toDate, _advanceType);
           // _listAdvance = _empBus.LoadAdvanceForEmployeeByType(_advanceType,(int)_employeeSalary.EmployeeID);
            employeeAdvanceDTOBindingSource.DataSource = _listAdvance;
            //employerDTOBindingSource.DataSource = _employeeSalary; ;
        }

        private static EmployeeAdvanceDTO ValidateInput(EmployeeAdvanceDTO employeeAdvance)
        {
            if (employeeAdvance.Reason == null) employeeAdvance.Reason = "";
            if (employeeAdvance.Note == null) employeeAdvance.Note = "";
           
            return employeeAdvance;
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
           
        }

        private void btnDeleteItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            int rowIndex = gridView1.FocusedRowHandle;
            var employeeAdvance = gridView1.GetRow(rowIndex) as EmployeeAdvanceDTO;
            if (employeeAdvance != null)
                if (MessageBox.Show(string.Format("Bạn có chắc chắn muốn xóa không?"), "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    bool success = _empBus.DeleteAdvance(employeeAdvance.AdvanceID);
                    if (success)
                    {
                        LoadData();
                    }
                }
        }

        private void AdvanceManagement_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(_advanceType == "Phụ Cấp")
            _employeeSalary.TotalAllowanceFormat = TotalAdvance(_listAdvance).ToString();
            if (_advanceType == "Ứng Lương")
            _employeeSalary.TotalAdvanceSalaryFormat = TotalAdvance(_listAdvance).ToString();
            if (_advanceType == "Thu Nợ Hộ")
                _employeeSalary.Debt1Format = TotalAdvance(_listAdvance).ToString();
            if (_advanceType == "Đền Vật Tư")
                _employeeSalary.Debt2Format = TotalAdvance(_listAdvance).ToString();
          
            var success = _empBus.UpdateEmployeeSalary(_employeeSalary);
            if (success)
            {
                //EmployeeExpenseReceipts.LoadData();
            }
            
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _isNew = true;
            gridView1.SetRowCellValue(e.RowHandle, "EmployeeID", _employeeSalary.EmployeeID);
            gridView1.SetRowCellValue(e.RowHandle, "FullName", _employeeSalary.Fullname);
            gridView1.SetRowCellValue(e.RowHandle, "Type", _advanceType);
            gridView1.SetRowCellValue(e.RowHandle, "DateAdvance", DateTime.Today);
        }

        private void AdvanceManagement_Load(object sender, EventArgs e)
        {
            LoadData();
            _isEdit = false;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (!_isNew)
            {
                var view = sender as ColumnView;
                var i = e.RowHandle;
                var employeeAdvance = gridView1.GetRow(i) as EmployeeAdvanceDTO;
                employeeAdvance = ValidateInput(employeeAdvance);
                if (employeeAdvance != null)
                {

                    if (employeeAdvance.TotalAdvance <= 0)
                    {

                        DialogResult result = MessageBox.Show("Bạn chưa nhập số tiền vào phiếu" + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        view.SetColumnError(view.Columns[1], "Bạn chưa nhập số tiền vào phiếu", ErrorType.Warning);
                        if (result == DialogResult.No)
                        {
                            _isUpdate = false;
                            view.ClearColumnErrors();
                            LoadData();
                            return;
                        }
                        else
                        {
                            _isUpdate = true;
                            gridView1.FocusedRowHandle = i;
                            gridView1.FocusedColumn = e.Column;
                            return;
                        }
                    }

                    if (!_empBus.UpdateEmployeeAdvance(employeeAdvance))
                    {
                        //MessageBox.Show("employeeAdvance" + employeeAdvance.AdvanceID + " 1" + employeeAdvance.EmployeeID + " 2" + employeeAdvance.TotalAdvance + "3 " + employeeAdvance.Note + "4 " + employeeAdvance.Reason + "5 " + employeeAdvance.DateAdvance + "6 " + employeeAdvance.Type);
                        MessageBox.Show("bạn hảy xem lại kết nối tới máy chủ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isUpdate = false;
                    }
                    else
                    {
                        alertControlMain.Show(this, Constants.CONFIRM, "Bạn Đã chỉnh sửa Thành Công!");
                        _isUpdate = false;
                        LoadData();

                    }
                }
            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (_isNew)
            
            
           {
                var view = sender as ColumnView;
                var i = e.RowHandle;
                var employeeAdvance = gridView1.GetRow(i) as EmployeeAdvanceDTO;
                employeeAdvance = ValidateInput(employeeAdvance);
                employeeAdvance.Type = _advanceType;
                employeeAdvance.EmployeeID = _employeeSalary.EmployeeID;
                if (employeeAdvance != null)
                {

                    if (employeeAdvance.TotalAdvance <= 0)
                    {

                        DialogResult result = MessageBox.Show("Bạn chưa nhập số tiền vào phiếu" + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        view.SetColumnError(view.Columns[1], "Bạn chưa nhập số tiền vào phiếu", ErrorType.Warning);
                        if (result == DialogResult.No)
                        {
                            _isNew = false;
                            view.ClearColumnErrors();
                            LoadData();
                            return;
                        }
                       
                    }

                    if (!_empBus.CreateEmployeeAdvance(employeeAdvance))
                    {
                       
                        MessageBox.Show("bạn hảy xem lại kết nối tới máy chủ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isNew = false;
                    }
                    else
                    {
                        alertControlMain.Show(this, Constants.CONFIRM, "Bạn Đã tạo mới Thành Công!");
                        _isNew = false;
                        LoadData();

                    }
                }
            }
        }

        private void btnEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            gridView1.OptionsBehavior.ReadOnly = false;
        }

        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {

            if (e.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            {

                gridView1.OptionsBehavior.ReadOnly = false;

            }
            else
            {
                gridView1.OptionsBehavior.ReadOnly = !_isEdit;
            }
        }
    }
}